import { useEffect, useState } from "react";
import { isFunction } from '@/utils/is/index'


export default function  useBottomFresh (pageSize:Number=10 , reqFunction:Function , params:Object={} , dataField:string='data'){
  const [pageIdx, setPageIdx] = useState(1)
  const [loading,setLoading] =  useState(false)
  const [isEnd,setIsEnd] = useState(false)
  const [list, setList] = useState([])

  async function loadNext(){
    if(isEnd || loading) return;

    setLoading(true)

    const {data}  = await reqFunction({...params, PageIndex: pageIdx, PageSize:pageSize})
    let inData;
    if(!dataField){
      inData = data
    }else{
      inData = data[dataField]
    }
    if(inData){
      setList([ ...list , ...inData.Items])
      setPageIdx(inData['PageIndex'])
      if(inData['TotalPage'] >= pageIdx){
        setIsEnd(true)
      }
    }
    setLoading(false)
  }

  function handleNextPage(){
    setPageIdx(pageIdx+1)
  }

  useEffect(()=>{
    setPageIdx(1)
    loadNext()
  },[pageSize])

  useEffect(()=>{
    loadNext()
  },[pageIdx])

  return isFunction(reqFunction) ? { pageIdx , loading,isEnd , error:null , list , handleNextPage } : { error:'请求函数不正确'}

}
